


from pyee import AsyncIOEventEmitter
from fastapi.encoders import jsonable_encoder


class PyeeTestError(Exception):
    pass


import asyncio
import logging

from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings
from typing import Union, Callable



class NamedEventEmitter(AsyncIOEventEmitter):
    def __init__(self, name, *args, **kwargs):
        self.name = name
        AsyncIOEventEmitter.__init__(self, *args, **kwargs)


class EventEmitterPluginClient(BasePlugin):
    # 设置插件默认的参数信息
    name = 'events插件'

    class EventsSettings(Settings):
        pass
        events_name: str = "events"

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        # self._pyee_events = NamedEventEmitter(loop=asyncio.get_event_loop(),name=self.configs.events_name)
        self._pyee_events = NamedEventEmitter(name=self.settings.events_name)
        # 当期的插件实例对象赋值
        self.app.pyee_events_plugin_client = self
        # 客户端对应内部对象
        self.app.state.pyee_events = self._pyee_events
        global global_event_emitter_client
        global_event_emitter_client = self

    @property
    def on(self):
        return self._pyee_events.on

    @property
    def once(self):
        return self._pyee_events.once

    def async_emit_evnet(self, event, payload):
        async def _emit_async():
            self._pyee_events.emit(event, jsonable_payload)

        jsonable_payload = jsonable_encoder(payload)
        log = logging.getLogger(__name__)
        log.info(f"Emitting '{event}' using emitter '{self._pyee_events.name}'")
        log.debug(jsonable_payload)
        loop = asyncio.get_event_loop()
        loop.create_task(_emit_async())


global_event_emitter_client: Union[Callable, EventEmitterPluginClient] = lambda: None